/**
 * 
 */
package zeroj.helper;

/**
 * @author LYL(lyl at bitcomm dot cn)
 * 
 * @since 1.0
 *
 * 2008-9-23
 */
public final class StringUtil {

	public static boolean isEmpty(String str) {
		
		return str == null || str.trim().length() == 0;
	}
	
	public static boolean lengthRange(String str, int min, int max) {
		
		if(isEmpty(str))
			return false;
		int len = str.trim().length();
		return len <= max && len >= min;
	}
	public static String trim(String str) {
		
		return str == null ? "" : str.trim();
	}
	public static String trimLower(String str) {
		
		return str == null ? "" : str.trim().toLowerCase();
	}
	public static int str2int(String str, int defaultValue) {
		
		str = trim(str);
		return str.length() == 0 ? defaultValue : Integer.parseInt(str);
	}
	public static int str2int(String str) {
		
		return str2int(str, 0);
	}
	public static long str2long(String str, long defaultValue) {
		str = trim(str);
		return str.length() == 0 ? defaultValue : Long.parseLong(str);
	}
	public static long str2long(String str) {
		
		return str2long(str, 0L);
	}
	public static boolean str2bool(String str, boolean defaultValue) {
		
		str = trim(str);
		return str.length() == 0 ? defaultValue 
				: ("yes".equalsIgnoreCase(str) || "true".equalsIgnoreCase(str) 
				|| "1".equals(str) || "on".equalsIgnoreCase(str));
	}
	public static boolean str2bool(String str) {
		return str2bool(str, false);
	}
	
	 public static String bytes2hex(byte[] bs) {
	        
		 StringBuilder ret = new StringBuilder(bs.length);
	     for (int i = 0; i < bs.length; i++) {
	     
	    	 String hex = Integer.toHexString(0x0100 + (bs[i] & 0x00FF)).substring(1);
	         ret.append((hex.length() < 2 ? "0" : "") + hex);
	     }
	     return ret.toString();
	}
	 
	public static byte[] hex2bytes(String hexString) {
		
		int len = hexString.length();
		byte[] bytes = new byte[len / 2];
		for(int i = 0; i < len; i += 2) {
			int value = Integer.valueOf("00" + hexString.substring(i, i + 2), 16);
			bytes[i / 2] = (byte)value;
		}
		return bytes;
	}
}
